import { HttpException, HttpStatus, Injectable,Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from './entities/user.entity';
import { Like, Repository } from 'typeorm';
import * as crypto from 'crypto';
import { RegisterDto } from './dto/register.dto';
import { LoginDto } from './dto/login.dto';
import { updataUserPassword } from './dto/updataUserPassword';
import { UpdateUser } from './dto/update.dot';

function md5(str){
  const hash = crypto.createHash('md5')
  hash.update(str)
  return hash.digest('hex')
}

@Injectable()
export class UserService {
  
  private logger = new Logger()

  @InjectRepository(User)

  private userPepostiory:Repository<User>
  // 用户注册
  async register(user:RegisterDto){
      const userObj =  await this.userPepostiory.findOneBy({
        username:user.username
      })
      if(userObj){
        throw new HttpException('用户已存在',200)
      }
      const newUser = new User()
      newUser.username = user.username
      newUser.password = md5(user.password)
      try {
        await this.userPepostiory.save(newUser);
        return '注册成功';
      } catch(e) {
        this.logger.error(e, UserService);
        return '注册失败';
      }
  }
  //用户登录
  async login(user:LoginDto) {
    const userObj = await this.userPepostiory.findOne({
      where:{
        username:user.username,
      },
      select: ['id','username', 'password','role','email','avatar','is_disable']
    })
    if(!userObj) throw new HttpException('用户不存在',200)
    if(userObj.is_disable != '0') throw new HttpException('该用户已被禁用',201)
    console.log('获取的用户密码',userObj)
    if(userObj.password !== md5(user.password)) throw new HttpException('密码错误',201)
    delete userObj.password
    return userObj
  }

  async getUserList(pageNo: number, pageSize: number,username:string,isDisable:string) {
    const skipCount = (pageNo - 1) * pageSize;

    const condition:any = {}

    if(username) {
      condition.username = Like(`%${username}%`);   
    }
    if(['0','1'].includes(isDisable)){
      condition.isDisable = isDisable; 
    }
    console.log('---',username)
    const [userList, totalCount] = await this.userPepostiory.findAndCount({
        skip: skipCount,
        take: pageSize,
        where: condition,
        order:{
          create_at: 'DESC'
        }
    });

    return {
      userList,
      totalCount
    }
  }

  async findUserDetailById(userId: number) {
    const userList = await this.userPepostiory.find({
      where: {
        id:userId
      }
    })
    if(!userList[0]){
      throw new HttpException('暂无该用户',HttpStatus.BAD_REQUEST)
    }
    return userList[0]
  }

  async updatePassword(updataUserPasswordDto:updataUserPassword) {
    //查询是否有该用户
    const userInfo = await this.findUserDetailById(updataUserPasswordDto.userId)
    userInfo.password = md5(updataUserPasswordDto.newPassword);
    try {
      await this.userPepostiory.save(userInfo);
      return '密码修改成功';
    } catch(e) {
      this.logger.error(e, UserService);
      return '密码修改失败';
    }

  }

  
  async update(updateUserDto:UpdateUser) {
    const userInfo = await this.findUserDetailById(updateUserDto.userId)
    if(updateUserDto.username){
      userInfo.username = updateUserDto.username
    }
    if(updateUserDto.email){
      userInfo.email = updateUserDto.email
    }
    if(updateUserDto.avatar){
      userInfo.avatar = updateUserDto.avatar
    }
    if(updateUserDto.is_disable){
      userInfo.is_disable = updateUserDto.is_disable
    }
    try {
      await this.userPepostiory.save(userInfo);
      return userInfo;
    } catch(e) {
      this.logger.error(e, UserService);
      return '修改失败';
    }
  }

  async delete(id: number) {
    const userInfo = await this.findUserDetailById(id)
    const data = await this.userPepostiory.delete(id)
    if(data.affected>0){
      return '删除成功'
    }
    return '删除失败'
  }
}
